import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Program:IntelliJ IDEA
 * @description:替换字符串中的括号内容
 * @author:香蕉你个啵娜娜 l.h-p@qq.com
 * @create:2023-01-12 23:34
 **/

public class Solution {
    public String evaluate(String s, List<List<String>> knowledge){
        Map<String, String> dict = new HashMap<String, String>();
        for (List<String> kd : knowledge) {
            dict.put(kd.get(0), kd.get(1));
        }
        boolean addKey = false;
        StringBuilder key = new StringBuilder();
        StringBuilder res = new StringBuilder();
        for (int i = 0; i<s.length(); i++){
            char c = s.charAt(i);
            if (c == '('){
                addKey = true;
            }else if (c == ')'){
                if (dict.containsKey(key.toString())){
                    res.append(dict.get(key.toString()));
                } else {
                    res.append('?');
                }
                addKey = false;
                key.setLength(0);
            } else {
                if (addKey){
                    key.append(c);
                } else {
                    res.append(c);
                }
            }
        }
        return res.toString();
    }
}
